package com.cloud.auth.translator;

import cn.hutool.core.util.StrUtil;
import com.cloud.common.core.base.ApiResponse;
import com.cloud.common.core.base.ApiResponseEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.common.exceptions.UnsupportedGrantTypeException;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
import org.springframework.stereotype.Component;

/**
 * @Description: 异常翻译器
 * @Auther: zhangxun
 * @Date: 2020/8/11 17:07
 */
@Slf4j
@Component
public class AuthWebResponseExceptionTranslator  implements WebResponseExceptionTranslator {
    @Override
    public ResponseEntity translate(Exception e) throws Exception {
        ResponseEntity.BodyBuilder status = ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR);
        ApiResponse<String> apiResponse = new ApiResponse<>();
        String message = "认证失败";
        log.error(message, e);
        if (e instanceof UnsupportedGrantTypeException) {
            return status.body(ApiResponse.respond(ApiResponseEnum.UNSUPPORTED_GRANT_TYPE));
        }
        if (e instanceof InvalidGrantException) {
            if (StrUtil.containsIgnoreCase(e.getMessage(), "Invalid refresh token")) {
                return status.body(ApiResponse.respond(ApiResponseEnum.INVALIDGRANT));
            }
            if (StrUtil.containsIgnoreCase(e.getMessage(), "locked")) {
                return status.body(ApiResponse.respond(ApiResponseEnum.ACCOUNT_LOCKED));
            }
            return status.body(ApiResponse.respond(ApiResponseEnum.PASSWORD_ERROR));
        }
        return status.body(ApiResponse.respond("认证失败"));
    }
}